package pure.engine.world 
{
	import flash.display.Sprite;
	import pure.engine.world.Mirror;
	import pure.engine.model.Model2D;
	import pure.engine.core.ns_despair;
	use namespace ns_despair;
	
	/**
	 * 图层容器
	 * [Author] - PURE
	 * 
	 * [Hint] - 图层直接与Mirror关联，深度排序，【小(内) → 大(外)】
	 */
final public class Layer extends Sprite 
{
	
	
	/**
	 * 加入残像
	 * 
	 * [Param] - mirror  残像
	 */
	ns_despair function addMirror(mirror:Mirror):void
	{
		m_mirrorList[m_numMirror++] = m_needSortMirrorList[m_numNeedSort++] = mirror;
		mirror.m_layer = this;
	}
	
	
	/**
	 * 移除残像
	 * 
	 * [Param] - mirror  残像
	 * 
	 * [Hint] - Model被kill时，关联的Mirror直接调用此方法.
	 */
	ns_despair function removeMirror(mirror:Mirror):void
	{
		var index:int = m_mirrorList.indexOf(mirror);
		
		m_mirrorList[index] = m_mirrorList[--m_numMirror];
		m_mirrorList.pop();
	}
	
	
	/**
	 * 加入重新排序残像
	 * 
	 * [Param] - mirror  残像
	 * 
	 * [Hint] - 此方法仅在世界主题更新使用，非更新时，需重新排序的残像数量为0.
	 */
	ns_despair function addNeedSortMirror(mirror:Mirror):void
	{
		m_needSortMirrorList[m_numNeedSort++] = mirror;
	}
	
	
	/**
	 * 刷新
	 */
	ns_despair function flush():void
	{
		var i:int, index:int;
		var mirror:Mirror;
		
		// 全部排序
		m_mirrorList.sortOn(m_sortProperty, Array.NUMERIC);
		for (i = 0; i < m_numNeedSort; i++)
		{
			mirror = m_needSortMirrorList[i];
			mirror.cachedIndex = m_mirrorList.indexOf(mirror);
		}
		
		// 二次排序
		m_needSortMirrorList.sortOn('cachedIndex', Array.NUMERIC);
		
		// 加入到图层
		for (i = 0; i < m_numNeedSort; i++)
		{
			mirror = m_needSortMirrorList[i];
			this.addChildAt(mirror, mirror.cachedIndex);
		}
		
		m_needSortMirrorList.length = m_numNeedSort = 0;
		m_dirty = false;
	}
	

	/**
	 * 清空
	 */
	ns_despair function clear():void
	{
		while (this.numChildren)
		{
			(removeChildAt(0) as Mirror).recycle();
		}
		m_mirrorList.length = m_numMirror = m_needSortMirrorList.length = m_numNeedSort = 0;
		m_dirty = false;
	}
	
	
	/**
	 * 回收
	 */
	ns_despair function recycle():void
	{
		clear();
		m_cachedLayerList.push(this);
	}
	
	
	
	/**
	 * 获取
	 */
	ns_despair static function getLayer():Layer
	{
		if (m_cachedLayerList[0])
		{
			return m_cachedLayerList.pop();
		}
		return new Layer;
	}
	
	
	
	
	//======================
	// Member
	//======================
	
	
	ns_despair static var m_cachedLayerList:Array = [];
	
	ns_despair static var m_sortProperty:Array;

	ns_despair var m_mirrorList:Array = [];  // 残像列表
	
	ns_despair var m_numMirror:int;
	
	ns_despair var m_needSortMirrorList:Array = [];  // 需要重新排序的残像列表

	ns_despair var m_numNeedSort:int;
	
	ns_despair var m_dirty:Boolean;

}

}